package cn.zhxu.data.snack3;

import org.noear.snack.ONode;
import org.noear.snack.core.NodeDecoder;
import org.noear.snack.core.NodeEncoder;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

public class TemporalCodec<T extends TemporalAccessor> implements NodeEncoder<T>, NodeDecoder<T> {

    private final DateTimeFormatter defaultFormatter;

    public TemporalCodec(String defaultFormat) {
        defaultFormatter = DateTimeFormatter.ofPattern(defaultFormat);
    }

    @Override
    public void encode(TemporalAccessor data, ONode node) {
        if (data == null) {
            node.val().setNull();
            return;
        }
        node.val().setString(defaultFormatter.format(data));
    }

    @Override
    @SuppressWarnings("unchecked")
    public T decode(ONode node, Type type) {
        if (type == LocalTime.class) {
            return (T) LocalTime.parse(node.getRawString(), defaultFormatter);
        }
        if (type == LocalDate.class) {
            return (T) LocalDate.parse(node.getRawString(), defaultFormatter);
        }
        if (type == LocalDateTime.class) {
            return (T) LocalDateTime.parse(node.getRawString(), defaultFormatter);
        }
        throw new IllegalStateException("不支持的日期时间类型：" + type);
    }

}
